<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       v-model="form"
                       @on-load="getPage"
                       @refresh-change="refreshChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="handleDel"
                       @sort-change="sortChange"
                       @search-change="searchChange">
              <template slot-scope="scope"
                        slot="menu">
                <el-button type="text"
                           icon="el-icon-s-claim"
                           size="mini"
                           plain
                           :style="{ display: visibleEdit }"
                           @click="editUserClass(scope.row,scope.index)">消课
                </el-button>
              </template>
            </avue-crud>
        </basic-container>
    </div>
</template>

<script>
    import {getPage, getObj, addObj, putObj, delObj} from '@/api/mall/usercard'
    import {tableOption} from '@/const/crud/mall/usercard'
    import {mapState,mapGetters} from 'vuex'
    import {getPage as getSyscustomer} from '@/api/upms/syscustomer'
    import {addObj as addUserclassinfo} from '@/api/mall/userclassinfo'


    export default {
        name: 'usercard',
        data() {
            return {
              visibleEdit:'',
                form: {},
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20, // 每页显示多少条
                    ascs: [],//升序字段
                    descs: []//降序字段
                },
                paramsSearch: {},
                tableLoading: false,
                tableOption: tableOption
            }
        },
        created() {
        },
        mounted: function () {
        },
        computed: {
          ...mapState({
            userInfo: state => state.user.userInfo
          }),
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.permissions['mall:usercard:add'] ? true : false,
                    delBtn: this.permissions['mall:usercard:del'] ? true : false,
                    editBtn: this.permissions['mall:usercard:edit'] ? true : false,
                    viewBtn: this.permissions['mall:usercard:get'] ? true : false
                };
            }
        },
        methods: {
          editUserClass: function (row) {
            let that = this
            if(row.activation > 0){
              that.$confirm('确认消课吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(function () {
                putObj({
                  id:row.id,
                  activation:row.activation - 1
                }).then(data => {
                  if(data.data.code === 0){
                    addUserclassinfo({
                      userCard:row.cardNo,
                      userName:that.userInfo.username,
                      className:'消课',
                      flag:'0'
                    });
                  }
                })
              }).then(data => {
                this.getPage(this.page)
              }).catch(function (err) {
              })
            }else{
              that.$message({
                showClose: true,
                message: '无法进行此操作',
              })
            }
          },
            searchChange(params,done) {
              params = this.filterForm(params)
              if(params.goodsName != undefined){
                params.goodsName = params.goodsName[0]
              }
              if(params.specifications != undefined){
                params.specifications = params.specifications[1]
              }
              if(params.cardType != undefined){
                let a = params.cardType[0]+","+params.cardType[1]
                params.cardType = a
              }
                this.paramsSearch = params
                this.page.currentPage = 1
                this.getPage(this.page, params)
                done()
            },
            sortChange(val) {
                let prop = val.prop ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase() : ''
                if (val.order == 'ascending') {
                    this.page.descs = []
                    this.page.ascs = prop
                } else if (val.order == 'descending') {
                    this.page.ascs = []
                    this.page.descs = prop
                } else {
                    this.page.ascs = []
                    this.page.descs = []
                }
                this.getPage(this.page)
            },
            getPage(page, params) {
              if(this.userInfo.categoryId != null && this.userInfo.categoryId !=""){
                let categoryFirst = {
                  categoryFirst:this.userInfo.categoryId
                }
                params = categoryFirst
              }
                this.tableLoading = true
                getPage(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    descs: this.page.descs,
                    ascs: this.page.ascs,
                }, params, this.paramsSearch)).then(response => {
                  for(let i = 0;i< response.data.data.records.length;i++){
                    if(response.data.data.records[i].cardType!=null){
                      response.data.data.records[i].cardType = response.data.data.records[i].cardType.split(",")
                    }
                  }
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.page.currentPage = page.currentPage
                    this.page.pageSize = page.pageSize
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading = false
                })
            },
            /**
             * @title 数据删除
             * @param row 为当前的数据
             * @param index 为当前删除数据的行数
             *
             **/
            handleDel: function (row, index) {
                let _this = this
                this.$confirm('是否确认删除此数据', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    _this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getPage(this.page)
                }).catch(function (err) {
                })
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate: function (row, index, done, loading) {
                putObj(row).then(response => {
                    this.$message({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    })
                    done()
                    this.getPage(this.page)
                }).catch(() => {
                    loading()
                })
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave: function (row, done, loading) {
              let that = this
              if(row.goodsName != undefined){
                row.goodsName = row.goodsName[0]
              }
              if(row.specifications != undefined){
                row.specifications = row.specifications[1]
              }
              getSyscustomer({
                phone:row.phone
              }).then(response => {
                if(response.data.data.records.length > 0){
                  row.syscustomerId = response.data.data.records[0].id
                }else {
                  row.syscustomerId = ""
                }
                addObj(row).then(response => {
                  this.$message({
                    showClose: true,
                    message: '添加成功',
                    type: 'success'
                  })
                  done()
                  this.getPage(this.page)
                }).catch(() => {
                  loading()
                })


              })





            },
            /**
             * 刷新回调
             */
            refreshChange(page) {
                this.getPage(this.page)
            }
        }
    }
</script>

<style lang="scss" scoped>
</style>
